package models

import (
	"time"

	"github.com/beego/beego/v2/client/orm"
)

type TExam struct {
	Id         int       `orm:"column(id);auto"`
	Title      string    `orm:"column(title);size(145);null" description:"标题"`
	Desc       string    `orm:"column(desc);size(245);null" description:"描述"`
	Createtime time.Time `orm:"column(createtime);type(date);null" description:"创建时间"`
	Enable     *int      `orm:"column(enable);null" description:"是否可用"`
	Questions  string    `orm:"column(questions);type(longtext);null" description:"试卷内容"`
	StartAt    string    `orm:"column(start_at);null" description:"开始时间"`
	EndAt      string    `orm:"column(end_at);null" description:"结束时间"`
}

func (t *TExam) TableName() string {
	return "t_exam"
}

func init() {
	orm.RegisterModel(new(TExam))
}

// AddTExam insert a new TExam into database and returns
// last inserted Id on success.
func AddTExam(m *TExam) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

// GetTExamById retrieves TExam by Id. Returns error if
// Id doesn't exist
func GetTExamById(id int) (v *TExam, err error) {
	o := orm.NewOrm()
	v = &TExam{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

// GetAllTExam retrieves all TExam matches certain condition. Returns empty list if
// no records exist
func GetAllTExam() (result []*TExam, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(TExam))
	_, err = qs.All(&result)
	return
}

// UpdateTExam updates TExam by Id and returns error if
// the record to be updated doesn't exist
func UpdateTExamById(m *TExam) (err error) {
	o := orm.NewOrm()
	v := TExam{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		if _, err = o.Update(m); err == nil {
			return nil
		}
	}
	return
}

// DeleteTExam deletes TExam by Id and returns error if
// the record to be deleted doesn't exist
func DeleteTExam(id int) (err error) {
	o := orm.NewOrm()
	v := TExam{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&TExam{Id: id}); err == nil {
			return nil
		}
	}
	return
}
